package com.myGroup.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myGroup.dto.CommentDTO;
import com.myGroup.pojo.Comment;
import com.myGroup.pojo.Likes;
import com.myGroup.pojo.R;
import com.myGroup.pojo.User;
import com.myGroup.service.CommentService;
import com.myGroup.service.LikesService;
import com.myGroup.service.UserService;
import com.myGroup.utils.ThreadLocalUtil;
import com.myGroup.vo.CommentVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@Api(tags = "评论相关接口")
@RequestMapping("/cmt")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    @Autowired
    private LikesService likesService;

//    private Integer userId;

    // 子评论默认显示3条
    final int defaultPage = 1;
    final int defaultPageSize = 3;

    /**
     * 分页获取评论数据
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping()
    @ApiOperation("评论分页查询")
    public R<Page> page(@RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "5") Integer pageSize) {

//        log.info("page={}, pageSize={}",page, pageSize);

        /**
         * 这个肯定第一个调用，所以在这里先拿到用户的id，后面就可以直接用了
         */
//        Map<String , Object> claims = ThreadLocalUtil.get();
//        this.userId = (Integer) claims.get("id");

        // 分页查询一级评论
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Comment> commentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        commentLambdaQueryWrapper.eq(Comment::getParentId, 0); // 查询一级评论
        commentService.page(pageInfo, commentLambdaQueryWrapper);

        List<Comment> records = pageInfo.getRecords(); // 一级评论的分页列表
        log.info("records：{}", records);


        List<CommentVO> commentVOList = new ArrayList<>(); // 要返回这个：一级评论VO列表

        for (Comment record : records) {
//            Integer id = record.getId(); // 当前这条一级评论的id

//            CommentVO commentVO = new CommentVO(); // 一级评论的vo对象

//            BeanUtils.copyProperties(record, commentVO); // * 先把相同的属性拷给commentVO
//            log.info("commentVO(id={}):{}", id, commentVO);

            // 构造一级评论VO其他属性

//            addChildren(commentVO, this.defaultPage, this.defaultPageSize); // * 子评论数组
//            // 查找当前评论的孩子列表（分页）
//            Page<Comment> commentPageInfo = new Page<>(this.defaultPage, this.defaultPageSize); // 1,3
//
//            commentService.page(commentPageInfo,
//                    new LambdaQueryWrapper<Comment>().eq(Comment::getParentId, id));
//
//            // 子评论列表(分页)
//            List<Comment> childrenList = commentPageInfo.getRecords();
//
//            commentVO.setReplyTotalCount((int) commentPageInfo.getTotal()); // * 子评论总数
//
//            // 构造子评论VO列表
//            List<CommentVO> childrenCommentVOList = new ArrayList<>();
//            for (Comment childrenComment : childrenList) {
//                CommentVO childrenCommentVO = new CommentVO(); // 子评论VO
//                BeanUtils.copyProperties(childrenComment, childrenCommentVO); // 先复制属性
//                // 构造其他属性
//                User user = userService.getById(childrenComment.getUserId());
//                childrenCommentVO.setNickName(user.getNickName()); // 子评论VO的用户昵称
//                childrenCommentVO.setAvatarUrl(user.getAvatar()); // 子评论VO的用户头像链接
//
//                if (childrenComment.getReplyUserId() != null) { // 子评论是可以没有 replyUserId 的
//                    User user1 = userService.getById(childrenComment.getReplyUserId());
//                    childrenCommentVO.setReplyUserNickname(user1.getNickName()); // 子评论VO的回复用户昵称
//                }
//
//                childrenCommentVOList.add(childrenCommentVO); // 加入子评论VO列表
//            }
//
//            commentVO.setChildren(childrenCommentVOList); // * 子评论数组

//            User user = userService.getById(record.getUserId());
//            commentVO.setNickName(user.getNickName()); // * 评论VO的用户昵称
//            commentVO.setAvatarUrl(user.getAvatar()); // * 评论VO的用户头像链接

            // 一级评论直接没有 replyUserId


            // 将Comment封装成CommentVO对象
            CommentVO commentVO = addChildren(record, this.defaultPage, this.defaultPageSize);

            commentVOList.add(commentVO);
        }

        pageInfo.setRecords(commentVOList);

        return R.success(pageInfo);
    }

    /**
     * 将Comment封装成CommentVO对象
     * page == 0 && pageSize == 0 表示查全部，否则分页
     *
     * @param comment comment对象
     * @param page 查询孩子数组的page，若=0表示查全部
     * @param pageSize 查询孩子数组的pageSize，若=0表示查全部
     */
    CommentVO addChildren(Comment comment, int page, int pageSize) {
        CommentVO commentVO = new CommentVO(); // 一级评论的vo对象

        BeanUtils.copyProperties(comment, commentVO); // * 先把相同的属性拷给commentVO


        // 要先给commentVO复制属性然后才能用
        Integer id = commentVO.getId();

        // 查找当前评论的孩子列表（分页）
        Page<Comment> commentPageInfo;
        if (page == 0 && pageSize == 0) { // 查全部
            commentPageInfo = new Page<>();
        } else {                          // 分页查
            commentPageInfo = new Page<>(page, pageSize); // 1,3
        }

        commentService.page(commentPageInfo,
                new LambdaQueryWrapper<Comment>().eq(Comment::getParentId, id));

        // 子评论列表(分页)
        List<Comment> childrenList = commentPageInfo.getRecords();

        commentVO.setReplyTotalCount((int) commentPageInfo.getTotal()); // * 子评论总数

        // 构造子评论VO列表
        List<CommentVO> childrenCommentVOList = new ArrayList<>();
        for (Comment childrenComment : childrenList) {
            CommentVO childrenCommentVO = new CommentVO(); // 子评论VO
            BeanUtils.copyProperties(childrenComment, childrenCommentVO); // 先复制属性
            // 构造其他属性
            User user = userService.getById(childrenComment.getUserId());
            childrenCommentVO.setNickName(user.getNickName()); // 子评论VO的用户昵称
            childrenCommentVO.setAvatarUrl(user.getAvatar()); // 子评论VO的用户头像链接

            if (childrenComment.getReplyUserId() != null) { // 子评论是可以没有 replyUserId 的
                User user1 = userService.getById(childrenComment.getReplyUserId());
                childrenCommentVO.setReplyUserNickname(user1.getNickName()); // 子评论VO的回复用户昵称
            }

            childrenCommentVOList.add(childrenCommentVO); // 加入子评论VO列表
        }

        commentVO.setChildren(childrenCommentVOList); // * 子评论数组

        User user = userService.getById(comment.getUserId());
        commentVO.setNickName(user.getNickName()); // * 评论VO的用户昵称
        commentVO.setAvatarUrl(user.getAvatar()); // * 评论VO的用户头像链接

        // * 一级评论直接没有 replyUserId

        return commentVO;
    }

    /**
     * 根据评论的id获取所有的回复
     *
     * @param id
     * @return
     */
    @GetMapping("/details/{id}")
    @ApiOperation("根据评论的id获取所有的回复")
    public R<CommentVO> details(@PathVariable Integer id) {
        // 根据id查询Comment
        LambdaQueryWrapper<Comment> commentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        commentLambdaQueryWrapper.eq(Comment::getId, id);
        Comment comment = commentService.getOne(commentLambdaQueryWrapper);

        // 组装成CommentVO
        CommentVO commentVO = addChildren(comment, 0, 0);

        return R.success(commentVO);
    }

    /**
     * 点赞
     *
     * @param comment
     * @return
     */
    @PutMapping("/like")
    @ApiOperation("点赞的接口")
    public R<List<Integer>> update(@RequestBody Comment comment) {
        Map<String , Object> claims = ThreadLocalUtil.get();
//        this.userId = (Integer) claims.get("id");
        Integer userId = (Integer) claims.get("id");

        // 构造点赞记录
        Likes like = new Likes();
        like.setUserId(userId);
        like.setCommentId(comment.getId());

        Comment previous = commentService.getById(comment.getId());
        if (previous.getLikeNum() < comment.getLikeNum()) {
            // 若点赞，增加记录
            likesService.save(like);
        } else {
            // 否则删除该条记录
            LambdaQueryWrapper<Likes> likesLambdaQueryWrapper = new LambdaQueryWrapper<>();
            likesLambdaQueryWrapper.eq(Likes::getUserId, userId)
                    .eq(Likes::getCommentId, comment.getId());
            likesService.remove(likesLambdaQueryWrapper);
        }

        // 修改评论记录
        commentService.updateById(comment);

        // 返回赞过的id数组
        return R.success(likesIdList());
    }

    /**
     * 返回赞过的id数组
     *
     * @return
     */
    private List<Integer> likesIdList() {
        Map<String , Object> claims = ThreadLocalUtil.get();
//        this.userId = (Integer) claims.get("id");
        Integer userId = (Integer) claims.get("id");

        LambdaQueryWrapper<Likes> likesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        likesLambdaQueryWrapper.eq(Likes::getUserId, userId);
        List<Likes> list = likesService.list(likesLambdaQueryWrapper);
        List<Integer> cIds = new ArrayList<>();
        for (Likes likes : list) {
            cIds.add(likes.getCommentId());
        }
        return cIds;
    }

    /**
     * 获取该用户点赞过的所有评论
     *
     * @return
     */
    @GetMapping("/ids")
    @ApiOperation("获取该用户点赞过的所有评论")
    public R<List<Integer>> getLikedIds() {
        return R.success(likesIdList());
    }


    @PutMapping("/add")
    @ApiOperation("添加评论")
    public R<String> add(@RequestBody CommentDTO commentDTO) {
        Map<String , Object> claims = ThreadLocalUtil.get();
//        this.userId = (Integer) claims.get("id");
        Integer userId = (Integer) claims.get("id");


        Comment newComment = new Comment();
        newComment.setUserId(userId);
        newComment.setLikeNum(0);
        newComment.setCommentContent(commentDTO.getCommentContent());
        newComment.setCreateTime(LocalDateTime.now());

        if (commentDTO.getReplyCommentId() == 0) { // 约定新增的评论这里是0
            // 新增的一级评论
            newComment.setParentId(0);

        } else {
            // 评论别人的评论
            Integer replyCommentId = commentDTO.getReplyCommentId();
            Comment replyComment = commentService.getById(replyCommentId);


            // 这里使用了getParentId来区分两种评论，小心点
            if (replyComment.getParentId() == 0) {
                // 是顶级评论
                newComment.setParentId(replyComment.getId());
            } else {
                // 是二级评论
                newComment.setParentId(replyComment.getParentId());
                newComment.setReplyCommentId(replyCommentId);
                newComment.setReplyUserId(replyComment.getUserId());
            }
        }

//        System.out.println(newComment);

        commentService.save(newComment);

        return R.success("添加成功");
    }
}
